namespace RBAC.Write.Api.Application.Handler
{
    using System;
    using System.Linq;
    using Microsoft.EntityFrameworkCore;
    using RBAC.Domain.HXJX;
    using RBAC.ErrorCode;
    using RBAC.Interstructrue;
    using RBAC.Write.Api.Application.Dto;
    using RBAC.Write.Api.Application.Interfaces;

    /// <summary>
    /// 生产工单（写侧）服务实现。
    /// 说明：Create 实现真实持久化；Update/Report 仍为占位，可后续完善。
    /// </summary>
    public class ProductionWorkOrderWriteService : IProductionWorkOrderWriteService
    {
        private readonly RBACDbContext _db;
        public ProductionWorkOrderWriteService(RBACDbContext db)
        {
            _db = db;
        }

        public APIResult<CreateWorkOrderResultDto> CreateProductionWorkOrder(CreateWorkOrderCommandDto cmd)
        {
            var res = new APIResult<CreateWorkOrderResultDto>();
            if (cmd == null || string.IsNullOrWhiteSpace(cmd.OrderCode))
            {
                res.Code = APIEnums.Error;
                res.Msg = "OrderCode 不能为空";
                res.Data = new CreateWorkOrderResultDto { OrderId = 0, CreateTime = DateTime.UtcNow };
                return res;
            }

            // 校验唯一工单号
            var exists = _db.ProductionWorkOrder.AsNoTracking().Any(x => x.OrderCode == cmd.OrderCode);
            if (exists)
            {
                res.Code = APIEnums.Error;
                res.Msg = $"工单号已存在: {cmd.OrderCode}";
                res.Data = new CreateWorkOrderResultDto { OrderId = 0, CreateTime = DateTime.UtcNow };
                return res;
            }

            // 映射主表
            var order = new ProductionWorkOrder
            {
                OrderCode = cmd.OrderCode,
                OrderType = cmd.OrderType,
                OrderDate = cmd.OrderDate,
                OrderStatus = string.IsNullOrWhiteSpace(cmd.OrderStatus) ? "开立" : cmd.OrderStatus,
                CustomerId = cmd.CustomerId,
                CustomerName = cmd.CustomerName,
                ProductId = cmd.ProductId,
                ProductCode = cmd.ProductCode,
                ProductName = cmd.ProductName,
                Spec = cmd.Spec,
                Unit = cmd.Unit,
                Quantity = cmd.Quantity,
                DeliveryDate = cmd.DeliveryDate,
                Priority = cmd.Priority,
                SalesPersonId = cmd.SalesPersonId,
                SalesPerson = cmd.SalesPerson,
                BusinessType = cmd.BusinessType,
                Remark = cmd.Remark
            };

            // 保存主表
            _db.ProductionWorkOrder.Add(order);
            _db.SaveChanges();

            // 子表：BOM
            if (cmd.BomItems != null && cmd.BomItems.Count > 0)
            {
                var bomEntities = cmd.BomItems.Select(x => new ProductionWorkOrderBomItem
                {
                    WorkOrderId = order.Id,
                    LineNo = x.LineNo,
                    MaterialId = x.MaterialId,
                    MaterialCode = x.MaterialCode,
                    MaterialName = x.MaterialName,
                    Spec = x.Spec,
                    Unit = x.Unit,
                    Qty = x.Qty,
                    LossRate = x.LossRate,
                    WarehouseId = x.WarehouseId,
                    WarehouseName = x.WarehouseName,
                    Remark = x.Remark
                }).ToList();
                _db.ProductionWorkOrderBomItem.AddRange(bomEntities);
            }

            // 子表：工序
            if (cmd.Processes != null && cmd.Processes.Count > 0)
            {
                // 简单保证序号唯一（如有重复，后者顺延）
                var used = cmd.Processes.Select(p => p.SeqNo).ToHashSet();
                int seq = 10;
                foreach (var p in cmd.Processes)
                {
                    if (p.SeqNo <= 0)
                    {
                        while (used.Contains(seq)) seq += 10;
                        p.SeqNo = seq;
                        used.Add(p.SeqNo);
                        seq += 10;
                    }
                }

                var procEntities = cmd.Processes.Select(x => new ProductionWorkOrderProcess
                {
                    WorkOrderId = order.Id,
                    SeqNo = x.SeqNo,
                    ProcessCode = x.ProcessCode,
                    ProcessName = x.ProcessName,
                    WorkCenterId = x.WorkCenterId,
                    WorkCenterName = x.WorkCenterName,
                    StdHours = x.StdHours,
                    Uom = x.Uom,
                    PlanStartTime = x.PlanStartTime,
                    PlanEndTime = x.PlanEndTime,
                    TransferQty = x.TransferQty,
                    GoodQty = x.GoodQty,
                    ScrapQty = x.ScrapQty,
                    WipQty = x.WipQty,
                    Remark = x.Remark
                }).ToList();
                _db.ProductionWorkOrderProcess.AddRange(procEntities);
            }

            // 子表：附件
            if (cmd.Attachments != null && cmd.Attachments.Count > 0)
            {
                var attEntities = cmd.Attachments.Select(x => new ProductionWorkOrderAttachment
                {
                    WorkOrderId = order.Id,
                    FileName = x.FileName,
                    FileType = x.FileType,
                    FileUrl = x.FileUrl,
                    Uploader = x.Uploader,
                    UploadTime = x.UploadTime,
                    Remark = x.Remark
                }).ToList();
                _db.ProductionWorkOrderAttachment.AddRange(attEntities);
            }

            _db.SaveChanges();

            res.Code = APIEnums.Success;
            res.Msg = string.Empty;
            res.Data = new CreateWorkOrderResultDto
            {
                OrderId = order.Id,
                CreateTime = DateTime.UtcNow
            };
            return res;
        }

        public APIResult<UpdateWorkOrderResultDto> UpdateProductionWorkOrder(UpdateWorkOrderCommandDto cmd)
        {
            // 占位实现：待后续完善
            var res = new APIResult<UpdateWorkOrderResultDto>
            {
                Code = APIEnums.Success,
                Msg = string.Empty,
                Data = new UpdateWorkOrderResultDto { UpdateTime = DateTime.UtcNow }
            };
            return res;
        }

        public APIResult<SubmitProductionReportResultDto> SubmitProductionReport(SubmitProductionReportDto cmd)
        {
            // 占位实现：待后续完善
            var res = new APIResult<SubmitProductionReportResultDto>
            {
                Code = APIEnums.Success,
                Msg = string.Empty,
                Data = new SubmitProductionReportResultDto { CurrentProcessStatus = "进行中", CurrentProgress = 0 }
            };
            return res;
        }
    }
}
